package com.rzjm.api.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rzjm.api.constant.ResponseCode;
import com.rzjm.api.entity.Charger;
import com.rzjm.api.entity.ChargerOrder;
import com.rzjm.api.netty.charger.ClientSocket;
import com.rzjm.api.netty.charger.SocketPool;
import com.rzjm.api.service.ChargerOrderService;
import com.rzjm.api.service.ChargerPortRecordService;
import com.rzjm.api.service.ChargerPowerRoleService;
import com.rzjm.api.service.ChargerService;
import com.rzjm.api.util.GsonResultBean;
import com.rzjm.api.util.Tools;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  通知公告类 相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/charger")//url:模块/资源/{}/细分
public class ChargerController extends BaseController {

    @Resource
    private ChargerService chargerService;
    @Resource
    private ChargerOrderService chargerOrderService;
    @Resource
    private ChargerPortRecordService portRecordService;
    @Resource
    private ChargerPowerRoleService powerRoleService;

    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    /**
     *  重新获取配置信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/test")
    public JSONObject test(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int charger_id = jsonRequest.containsKey("charger_id") ? jsonRequest.getInt("charger_id") : 0;
            String order_no = jsonRequest.containsKey("order_no") ? jsonRequest.getStr("order_no") : "";

            ChargerOrder chargerOrder = chargerOrderService.getOrderByOrderNo(order_no);
            double bb = portRecordService.getChargerCapacity(chargerOrder);

//            List<Double> powerList = portRecordService.getAllRecordPowers("00000001653989527702",60);
//            List<Double> powerList1 = portRecordService.getAllRecordPowers("00000001653989527702",10);

////          double slope1 = MathUtil.getPowerSlope(Arrays.asList(dd));
////          System.out.println("slope1:  " + slope1);
//            double slope = MathUtil.getPowerSlope(powerList);
//            double slope11 = MathUtil.getPowerSlope(powerList1);
//            System.out.println("slope11:  " + slope11);

//            QueryWrapper<Charger> qw = new QueryWrapper<>();
//            qw.lt("last_online_time", DateUtil.getAfterSecondsByOld(new Date(), - (10 * 60)));
//            List<Charger> chargers = chargerService.list(qw);
//            if(CollUtil.isNotEmpty(chargers)){
//                System.out.println("当前有" + chargers.size() + "台设备离线");
//                for(Charger charger : chargers){
//                    charger.setOnlineState(0);
//                    charger.setLastOfflineTime(new Date());
//                    chargerService.updateById(charger);
//                }
//            }


//            Charger charger = chargerService.getChargerInfoById(charger_id);
//            if(charger == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
//            }
//            map.put("charger",charger);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",bb),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  重新获取配置信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int charger_id = jsonRequest.containsKey("charger_id") ? jsonRequest.getInt("charger_id") : 0;

            Charger charger = chargerService.getChargerInfoById(charger_id);
            if(charger == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }
            map.put("charger",charger);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *   根据订单 发送开启充电命令
     * @param
     * @throws Exception
     */
    @PostMapping(value="/order/handleOp")
    public JSONObject orderHandleOp(@RequestBody String requestParam){
        JSONObject ret = null;
        Map<String,Object> map = new HashMap<>();
        try{
            System.out.println("接收充电命令参数：" + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getInt("order_id") : 0;
            String order = jsonRequest.containsKey("order") ? jsonRequest.getStr("order") : "10";

            ChargerOrder chargerOrder = chargerOrderService.findById(order_id);
            if(chargerOrder == null){
                System.out.println("订单不存在：" + requestParam);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"订单不存在"),true,true);
            }

            String message = "";
            int leftMinutes = chargerOrder.getBuyMinutes() - chargerOrder.getUseMinutes();

            //充电
            int  i = 0;
            if(order.equals("10")){
                List<ClientSocket> clientSocketList = SocketPool.getClientByDeviceNum(chargerOrder.getDeviceSn());
                for (ClientSocket clientSocket : clientSocketList) {
                    if (StrUtil.isNotEmpty(clientSocket.getTerminalNum()) && !clientSocket.getTerminalNum().equals("null")) {
                        //端口号,充电时间,订单编号
                        String data = String.format("%02d", chargerOrder.getDevicePointIndex()) + "," + leftMinutes + ","+ chargerOrder.getOrderNo().toUpperCase();
                        String orderParam = "MS" + order + chargerOrder.getDeviceSn() + "" + data + "ME";
                        System.out.println("开始充电命令: " + orderParam);
                        clientSocket.getChannel().writeAndFlush(orderParam);
                        message = "充电开启成功！";
                        i++;
                    }
                }
            }else if(order.equals("05")){
                chargerOrder.setRemark("主动结束充电");
                chargerOrderService.updateById(chargerOrder);

                List<ClientSocket> clientSocketList = SocketPool.getClientByDeviceNum(chargerOrder.getDeviceSn());
                for (ClientSocket clientSocket : clientSocketList) {
                    if (StrUtil.isNotEmpty(clientSocket.getTerminalNum()) && !clientSocket.getTerminalNum().equals("null")) {
                        //端口号,充电时间,订单编号
                        String data = String.format("%02d", chargerOrder.getDevicePointIndex());
                        String orderParam = "MS" + order + chargerOrder.getDeviceSn() + "" + data + "ME";
                        System.out.println("结束充电命令: " + orderParam);
                        clientSocket.getChannel().writeAndFlush(orderParam);
                        message = "充电结束成功！";
                        i++;
                    }
                }
            }

            if(i > 0){
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,message),true,true);
            }else{
                ret = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

    /**
     *  重置redis 数据
     * @param
     * @throws Exception
     */
    @GetMapping(value="/reset/redis/{id}")
    public JSONObject resetRedis(@PathVariable("id") Integer charger_id){
        JSONObject ret = null;
        try{
            Charger charger = chargerService.findById(charger_id);
            if(charger == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该设备不存在"),true,true);
            }

            //激活后清除设备缓存
            String key = "charger_id_" + charger.getId();
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(charger));
            System.out.println("设备id:" + charger_id + ",数据已重置");

            key = "charger_" + charger.getChargerSn();
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(charger));
            System.out.println("设备SN:" + charger.getChargerSn() + ",数据已重置");


            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }


    /**
     *  重置 充电 收费规则 缓存数据
     * @param
     * @throws Exception
     */
    @GetMapping(value="/reset/power/role/{type}")
    public JSONObject resetPowerRole(@PathVariable("type") Integer type){
        JSONObject ret = null;
        try{
            powerRoleService.resetRoleData("15","145",type);
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功"),true,false);
        }catch (Exception e){
            e.printStackTrace();
            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return ret;
    }

}
